<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  name: 'App',
  data() {
    return {
      socket: null
    }
  },
  computed: {
  },
  created() {
    this.$bus.$on('init_websocket', this.init_websocket)
  },
  beforeDestroy() {
    this.$bus.$off('init_websocket')
  },
  methods: {
    init_websocket(data) {
      if (this.socket) {
        this.socket.close()
        this.socket = null
      }
      //建立socket连接,并给请求头中添加token
      this.socket = new WebSocket(`ws://127.0.0.1:8888/ws/2?token=${data.token}`)
      this.socket.onopen = this.open
      this.socket.onmessage = this.getMessage
      this.socket.onclose = this.close
      this.socket.onerror = this.error
    },
    open() {
      console.log('连接成功')
    },
    close() {
      console.log('连接关闭')
    },
    error(err) {
      console.log('连接错误', err)
    },
    getMessage(message) {
      if (message.data) {
        const data = JSON.parse(message.data)
        console.log("收到服务器的websocket消息", data)
        switch (data.type) {
          case 1:
            this.$bus.$emit('order_new', data)
            this.$notify({
              title: '新订单',
              message: '这是一条新订单待接单消息',
              type: 'success',
              duration: 0
            })
            break
          case 4:
            // this.$bus.$emit('order_new', data)
            this.$notify({
              title: '连接失败',
              message: data.reason,
              type: 'error',
              duration: 0
            })
            break
        }
      }
    }
  }
}
</script>
